package com.dk.utils;

import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;


public class RSAUtil {
	public static final String KEY_ALGORITHM = "RSA";// 加密方式
	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;
	private static final String PUBLIC_KEY_STR = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiruUGAX7UJmiNerjYZ9+Imgmw5njvU7fVVAe0\r\n" + 
			"KbJB0paL/H+ylAbkZnWlAw7hFj3tEOpCYBIRPXURkevdi6n2lDWdkjfgGKhjWuu1NRyIKjN7E5T/\r\n" + 
			"EV9j/4pKeaGZKrEIAbrsVo4m3Hy9RAkP0JueMxu+zljGo9eTgjJfH7mxgQIDAQAB";
	private static final String PRIVATE_KEY_STR = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKKu5QYBftQmaI16uNhn34iaCbDm\r\n"
			+ "eO9Tt9VUB7QpskHSlov8f7KUBuRmdaUDDuEWPe0Q6kJgEhE9dRGR692LqfaUNZ2SN+AYqGNa67U1\r\n"
			+ "HIgqM3sTlP8RX2P/ikp5oZkqsQgBuuxWjibcfL1ECQ/Qm54zG77OWMaj15OCMl8fubGBAgMBAAEC\r\n"
			+ "gYAVvNLjY43D4UH1LaHHYNHQmeyTk6gzKneU7L5+x1eHThFJsTqK7RairEIqA2eYkfVCWRFEPzwK\r\n"
			+ "y7B54YqntsLF9jr9rFupmqQPJQWyeFKWOMbW0Wu51agTqYtjKicjVPxLqw8/OWQ6LxA5qCahtOWY\r\n"
			+ "S0elLKufgu36zsIMhLSAAQJBAN3xcp8cR994jnYgbUilj5Zk2+6WGkvaK3Cwr54TE8hS0oPD0Or2\r\n"
			+ "HB55IIc6iDjJ4BhQ/AKaAEURaClPX1EXdoECQQC7pYxYp/JuDSMt6Y1/3BMcaig2yHtuYI1vRq8/\r\n"
			+ "PCfGLtTGwoHdrhi8mVOVa6LSzeDPDJUBr/ovfR8xkk5WErsBAkAqhXO8YCK1AdfpcdT+MhoMak5o\r\n"
			+ "q4FmPupLsM40rtr/aj7C1+VS3swMWpCM1/35Q1QX1Iwzw2WB1g/qujY8xw4BAkEAgHpxBaK4UrGc\r\n"
			+ "DKuEvq6oRyRINHpASOrC7BWxl9JQSVl3Rj+XO3kgZsF0gTIZYcykyB8NRwJ+glVhLkfGaxiYAQJB\r\n"
			+ "ANyeW1CpdoTl4xFUqJLMLo2qspnnUWjH8q70Ry4En8BdYekGgXjcrAusQCg11w1c2667WtUSNNJd\r\n" + "vxz65oqsLaM=";

	// 获取公钥
	public static PublicKey getPublicKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	// 获取私钥
	public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	// ************************加密解密**************************
	public static byte[] encrypt(byte[] plainText) throws Exception {
		PublicKey publicKey = getPublicKey(PUBLIC_KEY_STR);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = plainText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		int i = 0;
		byte[] cache;
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptText = out.toByteArray();
		out.close();
		return encryptText;
	}

	public static byte[] decrypt(byte[] encryptText) throws Exception {
		PrivateKey privateKey = getPrivateKey(PRIVATE_KEY_STR);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int inputLen = encryptText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] plainText = out.toByteArray();
		out.close();
		return plainText;
	}

	public static void main(String[] args) {
		try {
			// 加密
			byte[] bs = encrypt("abc".getBytes());
			System.out.println(new String(bs));
			// 解密
			byte[] bs2 = decrypt(bs);
			System.out.println(new String(bs2));

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
}
